"""文本检测API端点"""

from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query

from app.models.enums import DetectionPlatform
from app.models.request import TextDetectionRequest, BatchDetectionRequest, DetectionHistoryRequest
from app.models.response import (
    TextDetectionResponse, BatchDetectionResponse, DetectionHistoryResponse,
    PlatformsResponse, DataResponse, ErrorResponse
)
from app.services.text_detection import TextDetectionService
from app.core.dependencies import get_current_user, get_pagination_params
from app.utils.logger import get_logger
from app.utils.exceptions import (
    PlatformNotSupportedException, TaskNotFoundException, 
    TextDetectionException
)

logger = get_logger("text_detection_api")
router = APIRouter()

# 全局服务实例
detection_service = TextDetectionService()


@router.post("/text/detect", response_model=TextDetectionResponse, summary="提交文本检测任务")
async def submit_text_detection(
    request: TextDetectionRequest,
    current_user: str = Depends(get_current_user)
):
    """
    提交文本检测任务
    
    - **text**: 待检测的文本内容（必填，1-50000字符）
    - **platform**: 检测平台（zhiwang/gezida/weipu）
    - **title**: 文本标题（可选，最长200字符）
    - **author**: 文本作者（可选，最长100字符）
    
    返回任务ID和初始状态信息
    """
    try:
        logger.info(f"用户 {current_user} 提交文本检测任务")
        
        result = await detection_service.submit_detection(request)
        
        logger.info(f"任务提交成功: {result.task_id}")
        return result
        
    except PlatformNotSupportedException as e:
        logger.error(f"平台不支持: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"不支持的检测平台: {str(e)}"
        )
    except TextDetectionException as e:
        logger.error(f"文本检测异常: {e}")
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=e.message
        )
    except Exception as e:
        logger.error(f"提交检测任务失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )


@router.get("/text/detect/{task_id}", response_model=TextDetectionResponse, summary="查询检测结果")
async def get_detection_result(
    task_id: str,
    current_user: str = Depends(get_current_user)
):
    """
    查询检测结果
    
    根据任务ID查询检测任务的当前状态和结果
    
    状态说明：
    - **pending**: 待处理
    - **processing**: 处理中
    - **completed**: 已完成
    - **failed**: 失败
    - **cancelled**: 已取消
    """
    try:
        logger.info(f"用户 {current_user} 查询检测结果: {task_id}")
        
        result = await detection_service.get_detection_result(task_id)
        
        return result
        
    except TaskNotFoundException as e:
        logger.error(f"任务未找到: {e}")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"任务 {task_id} 未找到"
        )
    except Exception as e:
        logger.error(f"查询检测结果失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )


@router.delete("/text/{task_id}", summary="取消检测任务")
async def cancel_detection_task(
    task_id: str,
    current_user: str = Depends(get_current_user)
):
    """
    取消检测任务
    
    取消正在进行的检测任务（仅对pending和processing状态有效）
    """
    try:
        logger.info(f"用户 {current_user} 取消检测任务: {task_id}")
        
        success = await detection_service.cancel_detection(task_id)
        
        if success:
            return {"success": True, "message": "任务已取消"}
        else:
            return {"success": False, "message": "任务取消失败"}
            
    except TaskNotFoundException as e:
        logger.error(f"任务未找到: {e}")
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"任务 {task_id} 未找到"
        )
    except Exception as e:
        logger.error(f"取消任务失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )


@router.post("/text/batch", response_model=BatchDetectionResponse, summary="批量检测任务")
async def submit_batch_detection(
    request: BatchDetectionRequest,
    current_user: str = Depends(get_current_user)
):
    """
    批量提交检测任务
    
    一次性提交多个文本检测任务（最多100个）
    """
    try:
        logger.info(f"用户 {current_user} 提交批量检测任务，数量: {len(request.texts)}")
        
        result = await detection_service.submit_batch_detection(request)
        
        logger.info(f"批量任务提交完成: {result.batch_id}")
        return result
        
    except Exception as e:
        logger.error(f"批量检测任务提交失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )


@router.get("/text/history", response_model=DetectionHistoryResponse, summary="获取检测历史")
async def get_detection_history(
    page: int = Query(1, ge=1, description="页码"),
    size: int = Query(10, ge=1, le=100, description="每页数量"),
    platform: Optional[DetectionPlatform] = Query(None, description="筛选平台"),
    current_user: str = Depends(get_current_user)
):
    """
    获取检测历史记录
    
    支持分页和平台筛选
    """
    try:
        logger.info(f"用户 {current_user} 获取检测历史")
        
        history = await detection_service.get_detection_history(page, size, platform)
        
        # 计算总数（这里简化处理，实际应该从数据库获取）
        total = len(history) if page == 1 else page * size
        
        return DetectionHistoryResponse(
            total=total,
            page=page,
            size=size,
            items=history
        )
        
    except Exception as e:
        logger.error(f"获取检测历史失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )


@router.get("/platforms", response_model=PlatformsResponse, summary="获取支持的检测平台")
async def get_supported_platforms():
    """
    获取支持的检测平台列表
    
    返回所有已配置的检测平台信息，包括可用状态和特性
    """
    try:
        logger.info("获取支持的检测平台")
        
        platforms = detection_service.get_available_platforms()
        
        return PlatformsResponse(
            platforms=platforms
        )
        
    except Exception as e:
        logger.error(f"获取平台列表失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        )


@router.get("/statistics", summary="获取统计信息")
async def get_statistics(
    current_user: str = Depends(get_current_user)
):
    """
    获取检测统计信息
    
    返回平台统计和使用情况
    """
    try:
        logger.info(f"用户 {current_user} 获取统计信息")
        
        stats = detection_service.get_platform_statistics()
        
        return DataResponse(
            data=stats
        )
        
    except Exception as e:
        logger.error(f"获取统计信息失败: {e}")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="服务器内部错误"
        ) 